package com.cz.nongyetongv5.receiver;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.activity.MainActivity;
import com.cz.nongyetongv5.activity.NewsListActivity;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.utils.ConfigUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * 推送的消息接收者
 *
 * @author MrWu
 *
 */
public class DataGetterReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        final Bundle bundle = intent.getExtras();
        // 当收到注册ID时候
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            // String regId = bundle
            // .getString(JPushInterface.EXTRA_REGISTRATION_ID);
            // send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
                .getAction())) {

            ConfigUtil configUtil = new ConfigUtil(context.getResources());

            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);

            if (extra != null) {

                try {
                    JSONObject extraJson = new JSONObject(extra);

                    JSONObject propertyObj = extraJson.getJSONObject("android");

                    String to_code = propertyObj.getString("region_code");

                    if (configUtil.getRegionCode().startsWith(to_code)) {

                        // 接收到定制的消息的时候
                        processCustomMessage(context, bundle);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
                .getAction())) {

            // 当收到推送下来的通知的时候,获取推送通知的ID
            // int notifactionId = bundle
            // .getInt(JPushInterface.EXTRA_NOTIFICATION_ID);

            ConfigUtil configUtil = new ConfigUtil(context.getResources());

            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);

            if (extra != null) {

                try {
                    JSONObject extraJson = new JSONObject(extra);

                    JSONObject propertyObj = extraJson.getJSONObject("android");

                    String to_code = propertyObj.getString("region_code");

                    if (configUtil.getRegionCode().startsWith(to_code)) {

                        // 接收到定制的消息的时候
                        processCustomMessage(context, bundle);

                        /**
                         * 进行用户登录的检测
                         */
                        new AsyncTask<Integer, Integer, User>() {

                            private User user = null;

                            @Override
                            protected User doInBackground(Integer... params) {

                                /**
                                 * 从shared中读取缓存的用户名和密码
                                 */
                                SharedPreferences dataSharedPreferences = context
                                        .getSharedPreferences(
                                                CommonConstants.SHARED_REFERENCES_TAG,
                                                Context.MODE_PRIVATE);

                                final String username = dataSharedPreferences
                                        .getString("username", null);
                                final String password = dataSharedPreferences
                                        .getString("password", null);

                                final String town_path_id = dataSharedPreferences
                                        .getString("town_path_id", null);

                                final String showname = dataSharedPreferences
                                        .getString("showname", null);

                                final String localPySimple = dataSharedPreferences
                                        .getString("localpysimple", null);

                                final double region_longitude = Double
                                        .parseDouble(dataSharedPreferences
                                                .getString("region_longitude",
                                                        null));

                                final double region_latitude = Double
                                        .parseDouble(dataSharedPreferences
                                                .getString("region_latitude",
                                                        null));

                                final int region_zoom = dataSharedPreferences
                                        .getInt("region_zoom", 13);

                                final boolean tester = dataSharedPreferences
                                        .getBoolean("tester", true);
                                final String realname = dataSharedPreferences.getString(
                                        "realname", null);

                                final String region_name = dataSharedPreferences.getString(
                                        "region_name", null);
                                /**
                                 * 信息都不为空
                                 */
                                if (username != null && password != null
                                        && town_path_id != null) {

                                    user = new User(username, password,
                                            town_path_id, showname,
                                            localPySimple, region_longitude,
                                            region_latitude, region_zoom,
                                            tester,realname,region_name);

                                } else {
                                    user = null;
                                }

                                return user;
                            }

                            @Override
                            protected void onPostExecute(User user) {

                                String title = bundle
                                        .getString(JPushInterface.EXTRA_TITLE);

                                String message = bundle
                                        .getString(JPushInterface.EXTRA_MESSAGE);

                                String extra = bundle
                                        .getString(JPushInterface.EXTRA_EXTRA);

                                String tickerText = context
                                        .getString(R.string.notification_ticker_default);

                                try {
                                    JSONObject extraJson = new JSONObject(extra);

                                    JSONObject propertyObj = extraJson
                                            .getJSONObject("android");

                                    if (!propertyObj.isNull("tickertext")) {
                                        tickerText = propertyObj
                                                .getString("tickertext");
                                    }

                                } catch (JSONException e) {
                                }

//                                NotificationManager notificationManager = (NotificationManager) context
                                //                                        .getSystemService(Context.NOTIFICATION_SERVICE);
                                //
                                //                                Notification notification = new Notification();
                                //
                                //                                notification.icon = R.drawable.ic_launcher;
                                //
                                //                                notification.tickerText = tickerText;
                                //
                                //                                notification.when = System.currentTimeMillis();
                                //
                                //                                notification.defaults = Notification.DEFAULT_ALL;
                                //
                                //                                final Intent pendingNotificationIntent = new Intent(
                                //                                        context,
                                //                                        com.cz.nongyetongv5.activity.NewsListActivity.class);
                                //
                                //                                pendingNotificationIntent.putExtra("from",
                                //                                        "notification");
                                //
                                //                                pendingNotificationIntent
                                //                                        .putExtra("user", user);
                                //
                                //                                // 当点击的时候的intent
                                //                                PendingIntent pendingIntent = PendingIntent
                                //                                        .getActivity(context, 0,
                                //                                                pendingNotificationIntent, 0);
                                //
                                //                                notification.setLatestEventInfo(context, title,
                                //                                        message, pendingIntent);
                                //
                                //                                notificationManager.notify(0, notification);
                                //
                                //
                                //
                                int icon = R.mipmap.ic_launcher;
                                Intent intent = new Intent(context, com.cz.nongyetongv5.activity.NewsListActivity.class);
                                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                                NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                                builder.setAutoCancel(true)
                                        .setDefaults(Notification.DEFAULT_ALL)
                                        .setWhen(System.currentTimeMillis())
                                        .setSmallIcon(icon)
                                        .setTicker(tickerText)
                                        .setContentTitle(title)
                                        .setContentText(message)
                                        .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
                                        .setContentIntent(contentIntent)
                                        .setContentInfo("Info");
                                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                                notificationManager.notify(1, builder.build());
                            }

                        }.execute();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
                .getAction())) {
            // 当点击通知的时候

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent
                .getAction())) {
            // 处理的回调函数

        }
    }

    private void processCustomMessage(Context context, Bundle bundle) {

        String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo> packageList = activityManager
                .getRunningTasks(100);

        /**
         * 当前显示在屏幕上的Activity
         */
        ComponentName currentTopActivityName = null;

        for (RunningTaskInfo info : packageList) {
            if (info.topActivity.getPackageName().equals(
                    context.getPackageName())) {
                currentTopActivityName = info.topActivity;
                break;
            }
        }

        if (currentTopActivityName != null
                && currentTopActivityName.getClassName().equals(
                MainActivity.class.getName())) {
            // 显示的是主页

            Intent intent = new Intent();
            intent.setAction(currentTopActivityName.getClassName());
            intent.putExtra("extra", extra);

            context.sendBroadcast(intent);

        } else if (currentTopActivityName != null
                && currentTopActivityName.getClassName().equals(
                NewsListActivity.class.getName())) {
            // 如果刚好是新闻列表页

            Intent intent = new Intent();
            intent.setAction(currentTopActivityName.getClassName());
            intent.putExtra("extra", extra);

            context.sendBroadcast(intent);

        } else {

            // 没有程序运行，进行顶部通知的显示,发送广播到处理通知的接受者
            Intent intent = new Intent();

            intent.setAction(JPushInterface.ACTION_NOTIFICATION_RECEIVED);

            for (String key : bundle.keySet()) {

                if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                    intent.putExtra(key, bundle.getInt(key));
                } else {
                    intent.putExtra(key, bundle.getString(key));
                }
            }

            context.sendBroadcast(intent);
        }

    }

}
